package io.gitee.tuo_tuo.jfinaldevassistance.common;

import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Page;

import java.util.HashMap;

/**
 * @author tuotuo
 * Description: 通用统一返回结果类
 */
@SuppressWarnings({"serial", "rawtypes", "unchecked"})
public class Rst extends HashMap{
	public static String CODE = "code";
	public static String MSG = "msg";
    protected static final int SUCCESS = 1; //成功
    protected static final int FAIL = -1; //失败
	public static final int NO_LOGIN = -401; //失败
	
	public Rst(int code){
		super.put(CODE, code);
	}
	
	public static Rst ok(){
		return Rst.ok("成功!");
	}

    public static Rst ok(String successMsg){
		return new Rst(SUCCESS).setMsg(successMsg);
	}
    
	public static Rst fail(){
		return Rst.fail("失败!");
	}
    
    public static Rst fail(String failMsg){
    	return new Rst(FAIL).setMsg(failMsg);
	}

	public static Rst parse(String jsonRst){
		return Json.getJson().parse(jsonRst, Rst.class);
//		throw new MethodNotImplementException("Rst.parse");
	}

	public static Rst create(boolean success, String successMsg, String failMsg){
		Rst rst = success ? Rst.ok().setMsg(successMsg) : Rst.fail().setMsg(failMsg);
		return rst;
	}
	
	public Rst setMsg(String msg){
		super.put(MSG, msg);
		return this;
	}
	
	public boolean isOk() {
		Integer code = (Integer)get(CODE);
		return code != null && code > 0;
	}

    public Rst setData(Object key, Object value) {
    	super.put(key, value);
        return this;
    }
    
	public Rst setPagedData(Page page) {
    	super.put("page", page);
        return this;
    }
    
    public Rst put(Rst rst){
    	rst.remove(CODE);
    	rst.remove(MSG);
    	super.putAll(rst);
    	return this;
    }
    
	public boolean notNull(Object key) {
		return get(key) != null;
	}
	
	public boolean isNull(Object key) {
		return get(key) == null;
	}
	
	public boolean isTrue(Object key) {
		Object value = get(key);
		return (value instanceof Boolean && ((Boolean)value == true));
	}
    
    
	public <T> T getAs(Object key) {
		return (T)get(key);
	}
	
	public String getStr(Object key) {
		return (String)get(key);
	}

	public Integer getInt(Object key) {
		return (Integer)get(key);
	}

	public Long getLong(Object key) {
		return (Long)get(key);
	}

	public Boolean getBoolean(Object key) {
		return (Boolean)get(key);
	}

}